package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.DWaybillFeeDetailCostTypeEnum;
import cn.huiyunche.base.service.interfaces.DWaybillFeeDetailService;
import cn.huiyunche.base.service.mappers.DWaybillFeeDetailMapper;
import cn.huiyunche.base.service.model.DWaybillFeeDetail;
import cn.huiyunche.base.service.model.DWaybillFeeDetailExample;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @FileName: cn.huiyunche.service.base.tms.interfaces.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/2 下午5:22
 */
@Service
public class DWaybillFeeDetailServiceImpl implements DWaybillFeeDetailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DWaybillFeeDetailServiceImpl.class);

    @Autowired
    private DWaybillFeeDetailMapper dWaybillFeeDetailMapper;

    @Override
    public Long add(DWaybillFeeDetail feeDetail) {
        LOGGER.info("add param : {}", feeDetail);
        if (null == feeDetail) {
            LOGGER.error("add param feeDetail must not be null");
            throw new IllegalArgumentException("费用详情不能为空");
        }

        dWaybillFeeDetailMapper.insertSelective(feeDetail);

        return feeDetail.getId();
    }

    @Override
    public List<DWaybillFeeDetail> getListByWaybillId(Long waybillId) {
        LOGGER.info("getListByWaybillId param : {}", waybillId);
        if (null == waybillId) {
            LOGGER.error("getListByWaybillId param waybillId must not be null");
            throw new IllegalArgumentException("运单主键不能为空");
        }

        DWaybillFeeDetailExample example = new DWaybillFeeDetailExample();
        example.createCriteria().andWaybillIdEqualTo(waybillId);

        List<DWaybillFeeDetail> list = dWaybillFeeDetailMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(list)) {

            LOGGER.error("getListByWaybillId list must not be null");
            throw new BusinessException("查询运单费用详情失败");
        }

        //过滤更新价格
        List<DWaybillFeeDetail> collect = list.stream().filter(f -> (DWaybillFeeDetailCostTypeEnum.RETURN_COST.getValue() + "").equals(f.getCostType())).collect(Collectors.toList());

        if ( CollectionUtils.isNotEmpty(collect) ) {
            return collect;
        }

        return list;
    }

}
